package com.anysoft.home.fragment;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.content.res.ColorStateList;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.anysoft.MentorConst;
import com.anysoft.utils.MentorLogger;
import com.facebook.drawee.backends.pipeline.Fresco;
import com.facebook.drawee.interfaces.DraweeController;
import com.facebook.drawee.view.SimpleDraweeView;
import com.anysoft.HostConstant;
import com.anysoft.R;
import com.anysoft.adapter.HomeFinancialNewAdapter;
import com.anysoft.adapter.SearchAdapter;
import com.anysoft.base.BaseFragment;
import com.anysoft.bean.AntiMoneyValidateBean;
import com.anysoft.bean.BannersBean;
import com.anysoft.bean.CompanyIntroBean;
import com.anysoft.bean.ListAnnouncemetsBean;
import com.anysoft.bean.QueryFinancialListBean;
import com.anysoft.bean.QueryFundInfoBean;
import com.anysoft.bean.QueryFundListBean;
import com.anysoft.bean.QueryManagerMoneyViewListBean;
import com.anysoft.bean.QueryRiskLevelBean;
import com.anysoft.bean.QueryThemeHotSpotListBean;
import com.anysoft.bean.QueryUserAssetsBean;
import com.anysoft.bean.UserBean;
import com.anysoft.event.HomeBannerLoginEvent;
import com.anysoft.event.InterfaceCallback;
import com.anysoft.guide.GuideAdapter;
import com.anysoft.home.HomeActivity;
import com.anysoft.linstener.OnNextLinstener;
import com.anysoft.me.config.CommentConfig;
import com.anysoft.user.UserInfoEditActivity;
import com.anysoft.user.UserSettingActivity;
import com.anysoft.utils.AESUtils;
import com.anysoft.utils.ActivityUtils;
import com.anysoft.utils.CommonUtil;
import com.anysoft.utils.GlideImageLoader;
import com.anysoft.utils.HttpUtils;
import com.anysoft.utils.PreferencesUtils;
import com.anysoft.utils.StringUtils;
import com.anysoft.utils.user.UserBeanUtil;
import com.anysoft.view.IcbcScrollListView;
import com.anysoft.view.LooperTextView;
import com.anysoft.view.MyViewPager;
import com.anysoft.view.PullToRefreshView;
import com.anysoft.view.dialog.IcbcDialog;
import com.anysoft.web.AssetsFundActivity;
import com.anysoft.web.AssetsFundDetailActivity;
import com.anysoft.web.BannerUrlActivity;
import com.anysoft.web.FinancialServicesActivity;
import com.anysoft.web.FinancialServicesListActivity;
import com.anysoft.web.FundDetailActivity;
import com.anysoft.web.IcbcDetailActivity;
import com.anysoft.web.SearchTradeNewActivity;
import com.anysoft.web.ThemeHotSpotActivity;
import com.anysoft.web.WisdomActivity;
import com.google.gson.Gson;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.cache.CacheMode;
import com.lzy.okgo.callback.StringCallback;
import com.lzy.okgo.model.Response;
import com.orhanobut.logger.Logger;
import com.rd.PageIndicatorView;
import com.youth.banner.Banner;
import com.youth.banner.BannerConfig;
import com.youth.banner.Transformer;
import com.youth.banner.listener.OnBannerListener;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.io.File;
import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import de.hdodenhof.circleimageview.CircleImageView;

import static com.anysoft.utils.user.UserBeanUtil.hasUser;

/**
 * 工银页面
 */
@SuppressLint("NewApi")
public class HomeTab extends BaseFragment implements PullToRefreshView.OnHeaderRefreshListener, View.OnClickListener {

    protected final String TAG = this.getClass().getSimpleName();
    private View root;

    /**
     * 下拉刷新控件
     */
    @BindView(R.id.pullToRefreshView)
    PullToRefreshView pullToRefreshView;
    /**
     * 未登录时  布局容器
     */
    @BindView(R.id.rl_home_no_login)
    RelativeLayout rl_home_no_login;
    /**
     * 未登录时  顶部容器
     */
    @BindView(R.id.ll_home_no_logo_title)
    RelativeLayout ll_home_no_logo_title;

    /**
     * 开户
     */
    @BindView(R.id.tv_home_open_account)
    TextView tv_home_open_account;
    /**
     * 客服
     */
    @BindView(R.id.image_home_custom_service1)
    ImageView image_home_custom_service1;
    /**
     * 登录
     */
    @BindView(R.id.btn_home_login)
    Button btn_home_login;
    /**
     * 现金快线七日年化
     */
    @BindView(R.id.tv_home_seven_the_year_val)
    TextView tv_home_seven_the_year_val;
    /**
     * 超级现金快线七日年化
     */
    @BindView(R.id.tv_home_super_seven_the_year_val)
    TextView tv_home_super_seven_the_year_val;

    /**
     * 已登录时  布局容器
     */
    @BindView(R.id.ll_total_account)
    LinearLayout ll_total_account;
    /**
     * 已登录时  顶部容器
     */
    @BindView(R.id.ll_home_logo_title)
    RelativeLayout ll_home_logo_title;
    /**
     * 用户头像
     */
    @BindView(R.id.civ_home_user_head)
    CircleImageView civ_home_user_head;
    /**
     * 用户名称
     */
    @BindView(R.id.tv_user_name)
    TextView tv_user_name;
    /**
     * 用户未进行风险评测
     */
    @BindView(R.id.tv_no_risk)
    TextView tv_no_risk;

    /**
     * 客服
     */
    @BindView(R.id.image_home_user_service2)
    ImageView image_home_user_service2;
    /**
     * 总资产
     */
    @BindView(R.id.tv_total_account_val)
    TextView tv_total_account_val;
    /**
     * 总资产-小数
     */
    @BindView(R.id.tv_total_account_decimal_val)
    TextView tv_total_account_decimal_val;

    /**
     * 是否显示总资产
     */
    @BindView(R.id.image_is_show_total_account)
    ImageView image_is_show_total_account;
    /**
     * 昨日收益
     */
    @BindView(R.id.tv_yesterday_income_val)
    TextView tv_yesterday_income_val;

    //////////////////////////////////////////////////////////
    /**
     * 公告-小喇叭
     */
    @BindView(R.id.image_home_notice)
    ImageView image_home_notice;

    /**
     * 公告标题
     */
    @BindView(R.id.tv_home_notice_content)
    LooperTextView tv_home_notice_content;

    /**
     * 在线专家
     */
    @BindView(R.id.ll_home_online_expert)
    LinearLayout ll_home_online_expert;

    ////////////////////////--主题热点-->
    /**
     * 主题热点动态布局
     */
    @BindView(R.id.ll_home_hot_spot_layout)
    LinearLayout ll_home_hot_spot_layout;

    ////////////////////////--理财视点->
    /**
     * 理财视点 更多
     */
    @BindView(R.id.tv_home_financial_more)
    TextView tv_home_financial_more;
    /**
     * 理财视点 列表
     */
    @BindView(R.id.lv_financial)
    IcbcScrollListView lv_financial;

    private QueryFinancialListBean beanFinancial;
    private HomeFinancialNewAdapter homeFinancialNewAdapter;
    /**
     * 总资产
     */
    private String sTotalAccount;
    /**
     * 主体热点list
     */
    private List<QueryThemeHotSpotListBean.DataBean.DataListBean> listThemeHotSpot;

    /**
     * 记录当前登录用户编号  如果切换用户
     */
    private String currLoginFundCustomerNo;

    @BindView(R.id.iv_leftButton_1)
    ImageView iv_leftButton_1;
    @BindView(R.id.leftButton_1)
    Button leftButton_1;
    @BindView(R.id.et_search_1)
    EditText et_search_1;
    @BindView(R.id.iv_leftButton_2)
    ImageView iv_leftButton_2;
    @BindView(R.id.leftButton_2)
    Button leftButton_2;
    @BindView(R.id.et_search_2)
    EditText et_search_2;
    @BindView(R.id.ll_all_fund_search)
    LinearLayout ll_all_fund_search;
    @BindView(R.id.ll_home_notice_container)
    LinearLayout ll_home_notice_container;
    @BindView(R.id.lv)
    ListView lv;
    @BindView(R.id.rl_vp_fund_home)
    RelativeLayout rl_vp_fund_home;
    @BindView(R.id.vp_quick_entry)
    MyViewPager vp_quick_entry;
    @BindView(R.id.pageIndicatorView_quick_entry)
    PageIndicatorView pageIndicatorView_quick_entry;
    @BindView(R.id.sdv_home_image)
    SimpleDraweeView sdv_home_image;

    @BindView(R.id.vp_home_banner)
    Banner vp_home_banner;

    private GuideAdapter adapter;
    private List<BannersBean.DataBean> bannerList;  //广告的数据集合
    private List<View> viewList = new ArrayList<>();

    private ArrayList<QueryFundListBean.DataBean> searchLists = new ArrayList<>();
    private ArrayList<QueryFundListBean.DataBean> list_all = new ArrayList<>(); //搜索的基金数据集合
    private SearchAdapter searchAdapter;
    private String icbc_content, icbcUrl;
    private BannersBean.DataBean bannersBean;
    private CompanyIntroBean companyIntroBean; //了解XXXXXX
    private HomeActivity activity;
    private boolean isCacheHomeFundList = false; //基金列表缓存标识
    private boolean isCacheHomeThemeHot = false;//主题热点缓存标识
    private boolean isCacheHomeNews = false;//新闻资讯缓存标识
    private boolean isCacheHomeNotices = false;//公告缓存标识
    private boolean isCacheHomeHomeBannerList = false;//广告缓存标识
    
    
    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        activity = (HomeActivity) context;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        activity.setOnNextLinstener(new OnNextLinstener() {
            @Override
            public void OnCancelNext() {
                openActivity(USER_EDIT);
            }

            @Override
            public void OnConfirmNext() {
            }

            @Override
            public void OndoConfirm() {

            }
        });
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        root = inflater.inflate(R.layout.main_tab_01, container, false);
        ButterKnife.bind(this, root);
        EventBus.getDefault().register(this);
        pullToRefreshView.setOnHeaderRefreshListener(this);
        pullToRefreshView.setIsCancleLoadMore();

        searchAdapter = new SearchAdapter(activity, searchLists);
        lv.setAdapter(searchAdapter);

        et_search_1.addTextChangedListener(new TextWatcher() {

            @Override
            public void onTextChanged(CharSequence arg0, int num1, int num2, int num3) {
                searchLists.clear();
                if (num1 == 0 && num3 == 0) {
                    ll_all_fund_search.setVisibility(View.GONE);
                    iv_leftButton_1.setVisibility(View.GONE);
                    leftButton_1.setVisibility(View.INVISIBLE);
                    tv_home_open_account.setVisibility(View.VISIBLE);
                }
                if (num3 != 0 || (num1 != 0 && num2 == 1)) {
                    ll_all_fund_search.setVisibility(View.VISIBLE);
                    iv_leftButton_1.setVisibility(View.VISIBLE);
                    leftButton_1.setVisibility(View.VISIBLE);
                    tv_home_open_account.setVisibility(View.GONE);
                    String searchStr = et_search_1.getText().toString();
                    if (!StringUtils.isNullOrEmpty(searchStr)) {
                        searchStr = searchStr.toUpperCase();
                    }
                    searchAdapter.setSearchStr(searchStr);
                    for (QueryFundListBean.DataBean fundBean : list_all) {
                        if (fundBean.getFundcode().toUpperCase().contains(searchStr) || fundBean.getFundname().toUpperCase().contains(searchStr)) {
                            searchLists.add(fundBean);
                        }
                    }
                }
                if (searchAdapter != null) {
                    searchAdapter.notifyDataSetChanged();
                }
            }

            @Override
            public void beforeTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) {
            }

            @Override
            public void afterTextChanged(Editable arg0) {
            }
        });

        et_search_1.setCursorVisible(false);

        et_search_1.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                et_search_1.setCursorVisible(true);
                return false;
            }
        });

        et_search_2.addTextChangedListener(new TextWatcher() {

            @Override
            public void onTextChanged(CharSequence arg0, int num1, int num2, int num3) {
                searchLists.clear();
                tv_no_risk.setVisibility(View.GONE);
                if (num1 == 0 && num3 == 0) {
                    ll_all_fund_search.setVisibility(View.GONE);
                    iv_leftButton_2.setVisibility(View.GONE);
                    leftButton_2.setVisibility(View.INVISIBLE);
                    civ_home_user_head.setVisibility(View.VISIBLE);
                    initTipState();
                }
                if (num3 != 0 || (num1 != 0 && num2 == 1)) {
                    if (isMoneyValidate || islevelValidate) {
                        tv_no_risk.setVisibility(View.GONE);
                    }
                    ll_all_fund_search.setVisibility(View.VISIBLE);
                    iv_leftButton_2.setVisibility(View.VISIBLE);
                    leftButton_2.setVisibility(View.VISIBLE);
                    civ_home_user_head.setVisibility(View.GONE);
                    String searchStr = et_search_2.getText().toString();
                    if (!StringUtils.isNullOrEmpty(searchStr)) {
                        searchStr = searchStr.toUpperCase();
                    }
                    searchAdapter.setSearchStr(searchStr);
                    for (QueryFundListBean.DataBean fundBean : list_all) {
                        if (fundBean.getFundcode().toUpperCase().contains(searchStr) || fundBean.getFundname().toUpperCase().contains(searchStr)) {
                            searchLists.add(fundBean);
                        }
                    }
                }
                if (searchAdapter != null) {
                    searchAdapter.notifyDataSetChanged();
                }
            }

            @Override
            public void beforeTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) {
            }

            @Override
            public void afterTextChanged(Editable arg0) {
            }
        });

        et_search_2.setCursorVisible(false);

        et_search_2.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                et_search_2.setCursorVisible(true);
                return false;
            }
        });
        setBannerContainerScale();
        initQuickEntry();
        return root;

    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        String userId = UserBeanUtil.getInstance().getLastLoginAndRecordUserId();
        if (ActivityUtils.isOpenGestureOrFingerPrintLogin(activity, userId)) {
            ActivityUtils.gotoLogin(activity, !StringUtils.isNullOrEmpty(userId), false, userId);
        }
    }

    @Override
    public void onResume() {
        super.onResume();
        if (!StringUtils.isNullOrEmpty(currLoginFundCustomerNo) && !currLoginFundCustomerNo.equals(activity.getFundCustomerNo())) {
            initControData();
        }
        currLoginFundCustomerNo = activity.getFundCustomerNo();
        initData(false);
    }

    @Override
    public void onPause() {
        super.onPause();
    }

    private void setBannerContainerScale() {
        ViewGroup.LayoutParams params = rl_vp_fund_home.getLayoutParams();
        int screenWidth = activity.getWindowManager().getDefaultDisplay().getWidth();
        params.height = (int) (screenWidth / 2.7);
        rl_vp_fund_home.setLayoutParams(params);
    }

    /**
     * 初始化快速入口
     */
    private void initQuickEntry() {
        adapter = new GuideAdapter();
        viewList.clear();
        viewList.addAll(createQuickEntryPageList());
        pageIndicatorView_quick_entry.releaseViewPager();
        vp_quick_entry.removeAllViews();
        adapter.setData(viewList);
        vp_quick_entry.setAdapter(adapter);
        pageIndicatorView_quick_entry.setViewPager(vp_quick_entry);
        pageIndicatorView_quick_entry.setCount(viewList.size());
    }

    private List<View> createQuickEntryPageList() {
        List<View> list = new ArrayList<>();
        for (int i = 0; i < 2; i++) {
            list.add(createQuickEntryPageView(i));
        }
        return list;
    }

    private View createQuickEntryPageView(int position) {
        View view = null;
        if (position == 0) {
            view = LayoutInflater.from(activity).inflate(R.layout.onepage_fragment_layout, null);
            TextView tv_home_buy = (TextView) view.findViewById(R.id.tv_home_buy);
            TextView tv_home_redeem = (TextView) view.findViewById(R.id.tv_home_redeem);
            TextView tv_home_salary = (TextView) view.findViewById(R.id.tv_home_salary);
            TextView tv_home_query = (TextView) view.findViewById(R.id.tv_home_query);
            TextView tv_home_open_account = (TextView) view.findViewById(R.id.tv_home_open_account);
            tv_home_buy.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) { //购买
                    ActivityUtils.gotoFundListActivity(getActivity());
                }
            });
            tv_home_redeem.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) { //赎回
                    HostConstant.SKIP_TYPE = "from_redeem";
                    if (activity.mentorApplication.needLogin()) {
                        ActivityUtils.gotoLogin(getActivity(), activity.hasUser(), false, activity.findUserId());
                    } else {
                        ActivityUtils.gotoAssetsFundActivity(getActivity());
                    }
                }
            });
            tv_home_salary.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) { //工资转入
                    HostConstant.SKIP_TYPE = "from_salary";
                    if (activity.mentorApplication.needLogin()) {
                        ActivityUtils.gotoLogin(getActivity(), activity.hasUser(), false, activity.findUserId());
                    } else {
                        ActivityUtils.gotoFixInvestmentAllActivity(getActivity());
                    }
                }
            });
            tv_home_query.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) { //交易查询
                    HostConstant.SKIP_TYPE = "from_query";
                    if (activity.mentorApplication.needLogin()) {
                        ActivityUtils.gotoLogin(getActivity(), activity.hasUser(), false, activity.findUserId());
                    } else {
                        activity.startActivity(new Intent().setClass(activity, SearchTradeNewActivity.class));
                    }
                }
            });
            tv_home_open_account.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) { //开户指引
                    ActivityUtils.gotoRegistrationProcessActivity(activity);
                }
            });

        } else {
            view = LayoutInflater.from(activity).inflate(R.layout.twopage_fragment_layout, null);
            TextView tv_home_transform = (TextView) view.findViewById(R.id.tv_home_transform);
            tv_home_transform.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) { //转换查询
                    ActivityUtils.gotoTransformActivity(activity);
                }
            });
        }
        return view;
    }


    /**
     * 获取基金列表
     */
    private void getInfos() {
        OkGo.<String>post(HostConstant.QUERY_FUNDLIST)
                .tag(this)
                .params(HttpUtils.getCommonParams(activity, null))
                .cacheKey(AESUtils.encrypt("isCacheHomeFundList", HostConstant.QUERY_FUNDLIST))
                .cacheMode(CacheMode.FIRST_CACHE_THEN_REQUEST)
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(Response<String> response) {
                        UpdateUI(response.body());
                        refreshComplete();
                    }

                    @Override
                    public void onCacheSuccess(Response<String> response) {
                        super.onCacheSuccess(response);
                        if (!isCacheHomeFundList) {
                            //一般来说,缓存回调成功和网络回调成功做的事情是一样的,所以这里直接回调onSuccess
                            onSuccess(response);
                            isCacheHomeFundList = true;
                        }
                    }

                    @Override
                    public void onError(Response<String> response) {
                        super.onError(response);
                        refreshComplete();
                    }

                    @Override
                    public void onFinish() {
                        refreshComplete();
                    }
                });
    }

    private void UpdateUI(String resultJson) {

        QueryFundListBean bean;

        try {
            bean = new Gson().fromJson(resultJson, QueryFundListBean.class);
        } catch (Exception e) {
            Logger.e(TAG, "Gson解析数据时发生异常");
            e.printStackTrace();
            return;
        }

        if (!CommonUtil.checkState(activity, bean, resultJson)) {
            return;
        }

        if (bean == null || bean.getData() == null || bean.getData().isEmpty() || bean.getData().size() < 1) {
            activity.showConfirmAlert(activity, "数据为空");
            return;
        }

        list_all.clear();

        for (QueryFundListBean.DataBean DataBean : bean.getData()) {
            list_all.add(DataBean);
        }

        lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> arg0, View arg1, int position, long arg3) {
                activity.collapseSoftInputMethod(lv.getWindowToken());

                gotoDetails(searchLists.get(position));
            }
        });

        et_search_1.setFocusable(true);
        et_search_1.setFocusableInTouchMode(true);
        et_search_1.requestFocus();
        et_search_1.findFocus();

        et_search_2.setFocusable(true);
        et_search_2.setFocusableInTouchMode(true);
        et_search_2.requestFocus();
        et_search_2.findFocus();
    }

    /**
     * 点击搜索的基金条目跳转到基金详情
     *
     * @param bean
     */
    private void gotoDetails(QueryFundListBean.DataBean bean) {
        et_search_1.setCursorVisible(false);
        et_search_2.setCursorVisible(false);
        Intent intent = new Intent().setClass(activity, FundDetailActivity.class);
        intent.putExtra("fundcode", bean.getFundcode());
        intent.putExtra("fundname", bean.getFundname());
        intent.putExtra("fundType", bean.getFundtype());
        intent.putExtra("mainTitle", bean.getFundname() + " " + bean.getFundcode());
        intent.putExtra("subTitle", bean.getFundstateDescription());
        startActivity(intent);
    }

    /**
     * 初始化控件数据为--
     */
    private void initControData() {

        activity.setUserLevel(null);
        String sDefaultData = "--";
        tv_yesterday_income_val.setText(sDefaultData);
        tv_total_account_decimal_val.setText("");
        sTotalAccount = sDefaultData;
        tv_total_account_val.setText("" + sTotalAccount);

        xjkxListBean = null;
        cjxjkxListBean = null;
        sYesterDayIncome = sDefaultData;//昨日收益
        sHomeCashTotal = sDefaultData;//现金快线 总额
        sHomeCash = sDefaultData;//现金快线 正负
        sHomeSuperCashTotal = sDefaultData;//超级现金快线 总额
        sHomeSuperCash = sDefaultData;//超级现金快线 正负

        refreshComplete();

    }

    /**
     * 是否是下拉刷新
     *
     * @param isPullRefresh
     */
    private void initData(boolean isPullRefresh) {
        if (isSearchLayoutShow()) {
            Log.e("========", "initData: ");
            hideSearchLayout();
        }
        if (activity.mentorApplication.needLogin()) {
            rl_home_no_login.setVisibility(View.VISIBLE);
            ll_home_no_logo_title.setVisibility(View.VISIBLE);
            ll_total_account.setVisibility(View.GONE);
            ll_home_logo_title.setVisibility(View.GONE);
            tv_no_risk.setVisibility(View.GONE);
        } else {
            rl_home_no_login.setVisibility(View.GONE);
            ll_home_no_logo_title.setVisibility(View.GONE);
            ll_total_account.setVisibility(View.VISIBLE);
            ll_home_logo_title.setVisibility(View.VISIBLE);
            tv_user_name.setText(activity.mentorApplication.userBean.getUserName());
            try {
                setIsShowTotalAccount(((HomeActivity) activity).getShowTotalAccountStatus());
            } catch (Exception e) {
                e.printStackTrace();
            }

            UserBean bean = activity.findUser(activity.findUserId());
            String pathUrl = "";
            if (bean != null) {
                pathUrl = bean.getUserImgPath();
                if (!TextUtils.isEmpty(pathUrl)) {
                    Logger.t("pathUrl").d(pathUrl);
                    Bitmap bitmap = getDiskBitmap(pathUrl);
                    if (bitmap != null) {
                        civ_home_user_head.setImageBitmap(bitmap);
                    }
                } else {
                    if ("0".equals(bean.getSex())) {//女
                        civ_home_user_head.setImageResource(R.mipmap.icon_user_w);
                    } else if ("1".equals(bean.getSex())) {//男
                        civ_home_user_head.setImageResource(R.mipmap.icon_user_m);
                    } else {
                        civ_home_user_head.setImageResource(R.mipmap.icon_user);
                    }
                }
            }
            if (isPullRefresh) {
                queryUserAssetsHome();
                queryAntiMoneyValidateHome();
                queryRiskLevelHome();
            }
        }

        if (isPullRefresh || XJKJDataBean == null) {
            queryFundInfoHome(HostConstant.XJKJ_CODE);

        }
        if (isPullRefresh || CJXJKJDataBean == null) {
            queryFundInfoHome(HostConstant.CJXJKJ_CODE);
        }
        if (isPullRefresh || listAnnouncemets == null) {
            listAnnouncemets();//公告
        }
        if (isPullRefresh || listThemeHotSpot == null) {
            queryThemeHotSpotList();//listThemeHotSpot //主题热点
        }
        if (isPullRefresh || listManagerMoneyView == null) {
            queryManagerMoneyViewList();//新闻资讯 listManagerMoneyView
        }

        if (isPullRefresh || bannerList == null) {
            requestBannerData(); //广告条
        }

        if (isPullRefresh || list_all == null || list_all.size() == 0) {
            getInfos();
        }
        if (isPullRefresh || companyIntroBean == null) {
            requestCompanyIntroData();
        }
    }

    /**
     * 获取了解XXXXXX入口的数据
     */
    private void requestCompanyIntroData() {
        OkGo.<String>post(HostConstant.QUERY_COMPANY_INTRO)
                .tag(this)
                .params(HttpUtils.getCommonParams(activity, null))
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(Response<String> response) {
                        updateUIcompanyIntro(response.body());
                    }


                    @Override
                    public void onError(Response<String> response) {
                        super.onError(response);
                        showToast("网络加载失败，请稍后再试!");
                    }

                    @Override
                    public void onFinish() {
                        super.onFinish();
                    }
                });
    }

    private void updateUIcompanyIntro(String response) {
        try {
            companyIntroBean = new Gson().fromJson(response, CompanyIntroBean.class);
        } catch (Exception e) {
            Logger.e("FundTab", "Gson解析数据时发生异常");
            e.printStackTrace();
            return;
        }
        if (!CommonUtil.checkState(activity, companyIntroBean, response)) {
            return;
        }

        if (companyIntroBean.getData() == null) {
            sdv_home_image.setVisibility(View.GONE);
            return;
        }
        String displayImageUrl = companyIntroBean.getData().getDisplayImage();
        if (StringUtils.isNullOrEmpty(displayImageUrl)) {
            sdv_home_image.setVisibility(View.GONE);
            return;
        }

//        GenericDraweeHierarchyBuilder builder = new GenericDraweeHierarchyBuilder(getResources());
//        GenericDraweeHierarchy hierarchy = builder.setFadeDuration(1000)
//                .build(); //设置淡入淡出显示时间
        sdv_home_image.setVisibility(View.VISIBLE);
        DraweeController controller = Fresco.newDraweeControllerBuilder()
                .setUri(Uri.parse(companyIntroBean.getData().getDisplayImage()))
                .setTapToRetryEnabled(false) //设置加载失败后能否重试
                .setOldController(sdv_home_image.getController())
                .build();
//
        sdv_home_image.setController(controller);
//        sdv_home_image.setHierarchy(hierarchy);
        sdv_home_image.setImageURI(Uri.parse(companyIntroBean.getData().getDisplayImage()));
        icbc_content = companyIntroBean.getData().getContent();
        icbcUrl = companyIntroBean.getData().getUrl();
    }

    /**
     * 请求banner的数据
     */
    private void requestBannerData() {
        Map<String, String> params = new HashMap<>();
        params.put("bannerType", "0");
        OkGo.<String>post(HostConstant.LIST_BANNERS)
                .tag(this)
                .cacheKey(AESUtils.encrypt("isCacheHomeHomeBannerList", HostConstant.LIST_BANNERS))
                .cacheMode(CacheMode.FIRST_CACHE_THEN_REQUEST)
                .params(HttpUtils.getCommonParams(activity, params))
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(Response<String> response) {
                        bannersUpdateUI(response.body());
                    }

                    @Override
                    public void onCacheSuccess(Response<String> response) {
                        super.onCacheSuccess(response);
                        if (!isCacheHomeHomeBannerList) {
                            onSuccess(response);
                            isCacheHomeHomeBannerList = true;
                        }
                    }

                    @Override
                    public void onError(Response<String> response) {
                        super.onError(response);
                        refreshComplete();
                    }

                    @Override
                    public void onFinish() {
                        super.onFinish();
                        refreshComplete();
                    }
                });
    }

    private void bannersUpdateUI(String resultJson) {
        bannerList = new ArrayList<>();
        bannerList.clear();
        viewList.clear();
        BannersBean bean;
        try {
            bean = new Gson().fromJson(resultJson, BannersBean.class);
        } catch (Exception e) {
            Logger.e("FundTab", "Gson解析数据时发生异常");
            e.printStackTrace();
            return;
        }

        if (!CommonUtil.checkState(activity, bean, resultJson)) {
            return;
        }

        if (bean.getData() == null || bean.getData().isEmpty()) {
            return;
        }

        bannerList.addAll(bean.getData());

        if (bannerList.size() > 0) {
            rl_vp_fund_home.setVisibility(View.VISIBLE);
        } else {
            rl_vp_fund_home.setVisibility(View.GONE);
        }
        initBannersData();
    }

    /**
     * 初始化广告数据
     */
    private void initBannersData() {
        String bannerTime = bannerList.get(0).getBannerIntervalTime();
        int bannerIntervalTime = 0;
        if (TextUtils.isEmpty(bannerTime)) {
            bannerIntervalTime = 5000;
        } else {
            bannerIntervalTime = Integer.parseInt(bannerTime) * 1000;
        }
//        vp_home_banner.setMinimumHeight(screenWidth * (378 / 80));
        //设置banner样式
        vp_home_banner.setBannerStyle(BannerConfig.CIRCLE_INDICATOR);
        //设置图片加载器
        vp_home_banner.setImageLoader(new GlideImageLoader());
        //设置图片集合
        vp_home_banner.setImages(bannerList);
        //设置banner动画效果
        vp_home_banner.setBannerAnimation(Transformer.Default);
        //设置自动轮播，默认为true
        vp_home_banner.isAutoPlay(true);
        //设置轮播时间
        vp_home_banner.setDelayTime(bannerIntervalTime);
        //设置指示器位置（当banner模式中有指示器时）
        vp_home_banner.setIndicatorGravity(BannerConfig.CENTER);
        vp_home_banner.setOnBannerListener(new OnBannerListener() {
            @Override
            public void OnBannerClick(int position) {
                bannersBean = bannerList.get(position);
                if (!TextUtils.isEmpty(bannersBean.getBannerUrl())) {
                    String web_url = bannersBean.getBannerUrl();
                    if (web_url.contains("fundDetail")) {
                        String url = null;
                        try {
                            url = URLDecoder.decode(web_url, "utf-8");
                        } catch (UnsupportedEncodingException e) {
                            e.printStackTrace();
                        }
                        MentorLogger.Log(TAG, "url=" + url);
                        String fundcode;
                        String fundType;
                        String mainTitle;
                        String subTitle;
                        Map<String, String> map = new HashMap<>();
                        String[] params = url.split("\\?")[1].split("&");
                        for (int i = 0; i < params.length; i++) {
                            //System.out.println("params--" + params[i]);
                            String key = params[i].split("=")[0];
                            String value = "";
                            try {
                                value = params[i].split("=")[1];
                            } catch (Exception exception) {
                                MentorLogger.Log(TAG, "value为null");
                            }
                            map.put(key, value);
                        }
                        fundcode = map.get("fundCode");
                        fundType = map.get("fundType");
                        mainTitle = map.get("fundName") + "  " + map.get("fundCode");
                        subTitle = map.get("fundstateDescription");

                        Intent mIntent = new Intent();
                        mIntent.setClass(getActivity(), FundDetailActivity.class);
                        mIntent.putExtra("fundcode", fundcode);
                        mIntent.putExtra("fundType", fundType);
                        mIntent.putExtra("fundname", map.get("fundName"));
                        mIntent.putExtra("mainTitle", mainTitle);
                        mIntent.putExtra("subTitle", subTitle);
                        startActivity(mIntent);
                    } else {
                        String isLogin = bannersBean.getIsLogin();
                        if (activity.mentorApplication.needLogin() && "1".equals(isLogin)) {
                            HostConstant.SKIP_TYPE = "from_home_banner";
                            ActivityUtils.gotoLogin(activity, hasUser(), false, activity
                                    .findUserId());
                        } else {
                            gotoBannerUrlActivity(bannersBean);
                        }
                    }
                } else if (!TextUtils.isEmpty(bannersBean.getContent())) {
                    String isLogin = bannersBean.getIsLogin();
                    if (activity.mentorApplication.needLogin() && "1".equals(isLogin)) {
                        HostConstant.SKIP_TYPE = "from_home_banner";
                        ActivityUtils.gotoLogin(activity, hasUser(), false, activity
                                .findUserId());
                    } else {
                        gotoBannerUrlActivity(bannersBean);
                    }
                }
            }
        });
        //banner设置方法全部调用完毕时最后调用
        vp_home_banner.start();
    }

    private void gotoBannerUrlActivity(BannersBean.DataBean bean) {
        Intent intent = new Intent();
        intent.setClass(activity, BannerUrlActivity.class);
        if (!TextUtils.isEmpty(bean.getBannerUrl())) {
            String params = "";
            if (!bean.getBannerUrl().contains("?")) {
                params = "?";
            } else {
                if (bean.getBannerUrl().endsWith("?")) {
                    params = "";
                } else {
                    params = "&";
                }
            }
            intent.putExtra("bannerUrl", bean.getBannerUrl() + params);
        } else if (!TextUtils.isEmpty(bean.getContent())) {
            intent.putExtra("content", bean.getContent());
        }
        if (!StringUtils.isNullOrEmpty(bean.getBannerTitle())) {
            intent.putExtra("bannerTitle", bean.getBannerTitle() + "");
        }
        if (!StringUtils.isNullOrEmpty(bean.getBannerDescription())) {
            intent.putExtra("bannerDescription", bean.getBannerDescription());
        }

        if (!StringUtils.isNullOrEmpty(bean.getBannerPicture())) {
            intent.putExtra("bannerPicture", bean.getBannerPicture());
        }
        activity.startActivity(intent);
    }

    /**
     * 获取到保存到本地的头像
     *
     * @param pathString
     * @return bitmap
     */
    private Bitmap getDiskBitmap(String pathString) {
        Bitmap bitmap = null;
        try {
            File file = new File(pathString);
            if (file.exists()) {
                bitmap = BitmapFactory.decodeFile(pathString);
            }
        } catch (Exception e) {
        }
        return bitmap;
    }

    /**
     * 生成textview
     *
     * @param index
     * @param text
     * @return
     */
    private TextView generTextViewFlag(int index, String text) {
        if (activity == null) {
            MentorLogger.LogJson(TAG, "activity为空");
            return null;
        }
        TextView tv = new TextView(activity);
        LinearLayout.LayoutParams paramsHotTextFalg = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
        paramsHotTextFalg.leftMargin = (index == 0 ? 0 : 20);
        tv.setGravity(Gravity.CENTER_VERTICAL);
        Resources resource = (Resources) activity.getBaseContext().getResources();
//        ColorStateList csl = (ColorStateList) resource.getColorStateList(R.color.bg_tag_red);
        ColorStateList csl = (ColorStateList) resource.getColorStateList(R.color.white);
        tv.setTextColor(csl);
        tv.setPadding(8, 4, 8, 4);
//        tv.setPadding(5, 3, 5, 3);
        tv.setTextSize(10);
        tv.setBackgroundResource(R.drawable.home_hot_flag_style_rectangle);
//        tv.setBackgroundResource(R.drawable.home_hot_flag_style);
        tv.setLayoutParams(paramsHotTextFalg);
        tv.setText(text + "");
        return tv;
    }

    private void showToast(String msg) {
        if (StringUtils.isNullOrEmpty(msg)) {
            return;
        }
        if (msg.contains("网络加载失败，请稍后再试") || MentorConst.INTERNET_ERROR.equals(msg)) {
            return;
        }
        Toast.makeText(activity, msg + "", Toast.LENGTH_SHORT).show();
    }

    @OnClick({R.id.tv_home_open_account, R.id.image_home_custom_service1, R.id.image_home_user_service2,
            R.id.btn_home_login, R.id.civ_home_user_head, R.id.image_is_show_total_account, R.id.rl_is_show_total_account,
            R.id.tv_home_notice_content, R.id.tv_home_financial_more, R.id.image_home_notice, R.id.rl_no_logon_xjkx_layout,
            R.id.rl_no_logon_cjxjkx_layout, R.id.ll_home_online_expert, R.id.tv_total_account_val, R.id.ll_total_account,
            R.id.leftButton_1, R.id.leftButton_2, R.id.tv_no_risk, R.id.ll_mx, R.id.sdv_home_image, R.id.ll_income_container})
    public void onClick(View v) {
        if (activity != null && !activity.isFastDoubleClick()) {
            switch (v.getId()) {
                case R.id.ll_income_container: //累计收益提示
                    activity.showTotalIncomAlert(activity.getString(R.string.total_incom_desc));
                    break;
                case R.id.sdv_home_image: //了解XXXXXX
                    Intent intent = new Intent(activity, IcbcDetailActivity.class);
                    intent.putExtra("icbcUrl", icbcUrl);
                    intent.putExtra("content", icbc_content);
                    startActivity(intent);
                    break;
                case R.id.tv_home_open_account://开户
                    openActivity(REGISTER);
                    break;
                case R.id.image_home_custom_service1://客服
                case R.id.image_home_user_service2:
                    openActivity(SERVICES);
                    break;
                case R.id.btn_home_login://登录
                    openActivity(LOGIN);
                    break;
                case R.id.civ_home_user_head://用户头像
                    openActivity(CLICK_USER_HEAD);
                    break;
                case R.id.image_is_show_total_account: //是否显示总资产
                case R.id.rl_is_show_total_account: //是否显示总资产
                    try {
                        ((HomeActivity) activity).isShowTotalAccount();
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    break;
                case R.id.tv_home_notice_content://公告标题
                case R.id.image_home_notice://公告小喇叭
//                    Intent intentList = new Intent(activity, AnnouncemetsListActivity.class);
//                    intentList.putExtra("listAnnouncemets", (Serializable) listAnnouncemets);
//                    startActivity(intentList);
                    break;
                case R.id.tv_home_financial_more://理财视点更多
                    openActivity(FINANCIAL_MORE);
                    break;
                case R.id.rl_no_logon_xjkx_layout://现金快线布局容器
                    BigDecimal decimalXJKX = new BigDecimal(0);
                    try {
                        decimalXJKX = new BigDecimal(sHomeCashTotal.toString().replaceAll(",", ""));
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    if (xjkxListBean == null || decimalXJKX.doubleValue() == 0) {
                        startFundDatile(XJKJDataBean);
                        return;
                    }
                    Intent intent_xjkx_assets = new Intent(activity, AssetsFundDetailActivity.class);

                    intent_xjkx_assets.putExtra("openType", "param");
                    intent_xjkx_assets.putExtra("fundcode", HostConstant.XJKJ_CODE);
                    intent_xjkx_assets.putExtra("fundname",
                            TextUtils.isEmpty(xjkxListBean.getFundName()) ? "" : xjkxListBean.getFundName());
                    intent_xjkx_assets.putExtra("fundState",
                            TextUtils.isEmpty(xjkxListBean.getFundStateId()) ? "" : xjkxListBean.getFundStateId());
                    intent_xjkx_assets.putExtra("fundstateid",
                            TextUtils.isEmpty(xjkxListBean.getFundStateId()) ? "" : xjkxListBean.getFundStateId());
                    intent_xjkx_assets.putExtra("fundType",
                            TextUtils.isEmpty(xjkxListBean.getFundType()) ? "" : xjkxListBean.getFundType());
                    intent_xjkx_assets.putExtra("shareClass",
                            TextUtils.isEmpty(xjkxListBean.getShareClass()) ? "" : xjkxListBean.getShareClass());
                    intent_xjkx_assets.putExtra("fundrisklevel",
                            TextUtils.isEmpty(xjkxListBean.getFundrisklevel()) ? "" : xjkxListBean.getFundrisklevel());
                    intent_xjkx_assets.putExtra("fundstateDescription",
                            TextUtils.isEmpty(xjkxListBean.getFundstateDescription()) ? "" : xjkxListBean.getFundstateDescription());
                    startActivity(intent_xjkx_assets);

                    break;
                case R.id.rl_no_logon_cjxjkx_layout://超级现金快线布局容器

                    BigDecimal decimalCJXJKX = new BigDecimal(0);
                    try {
                        decimalCJXJKX = new BigDecimal(sHomeSuperCashTotal.toString().replaceAll(",", ""));
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    if (cjxjkxListBean == null || decimalCJXJKX.doubleValue() == 0) {
                        startFundDatile(CJXJKJDataBean);
                        return;
                    }
                    Intent intent_cjxjkx_assets = new Intent(activity, AssetsFundDetailActivity.class);
                    intent_cjxjkx_assets.putExtra("openType", "param");
                    intent_cjxjkx_assets.putExtra("fundcode", HostConstant.CJXJKJ_CODE);
                    intent_cjxjkx_assets.putExtra("fundname",
                            TextUtils.isEmpty(cjxjkxListBean.getFundName()) ? "" : cjxjkxListBean.getFundName());
                    intent_cjxjkx_assets.putExtra("fundState",
                            TextUtils.isEmpty(cjxjkxListBean.getFundStateId()) ? "" : cjxjkxListBean.getFundStateId());


                    intent_cjxjkx_assets.putExtra("fundType",
                            TextUtils.isEmpty(cjxjkxListBean.getFundType()) ? "" : cjxjkxListBean.getFundType());
                    intent_cjxjkx_assets.putExtra("fundstateid",
                            TextUtils.isEmpty(cjxjkxListBean.getFundStateId()) ? "" : cjxjkxListBean.getFundStateId());
                    intent_cjxjkx_assets.putExtra("shareClass",
                            TextUtils.isEmpty(cjxjkxListBean.getShareClass()) ? "" : cjxjkxListBean.getShareClass());
                    intent_cjxjkx_assets.putExtra("fundrisklevel",
                            TextUtils.isEmpty(cjxjkxListBean.getFundrisklevel()) ? "" : cjxjkxListBean.getFundrisklevel());

                    intent_cjxjkx_assets.putExtra("fundstateDescription",
                            TextUtils.isEmpty(cjxjkxListBean.getFundstateDescription()) ? "" : cjxjkxListBean.getFundstateDescription());
                    startActivity(intent_cjxjkx_assets);
                    break;
                case R.id.ll_home_online_expert://在线专家
                    if (activity.mentorApplication.needLogin()) {
                        openActivity(LOGIN);
                    } else {
                        if (StringUtils.isNullOrEmpty(activity.getUserLevel())) {//未做评测
                            activity.startRiskActivity(null);
                        } else {
                            activity.startActivity(new Intent().setClass(activity, WisdomActivity.class));
                        }
                    }
                    break;
                case R.id.tv_total_account_val://总资产
                case R.id.ll_total_account://总资产
                case R.id.ll_mx:
                    if (activity.mentorApplication.needLogin()) {
                        ActivityUtils.gotoLogin(activity, hasUser(), false, activity.findUserId());
                        return;
                    }
                    activity.startActivity(new Intent().setClass(activity, AssetsFundActivity.class));//进全部资产
                    break;
                case R.id.leftButton_1:
                    activity.collapseSoftInputMethod(lv.getWindowToken());
                    et_search_1.setText("");
                    et_search_1.setCursorVisible(false);
                    break;
                case R.id.leftButton_2:
                    activity.collapseSoftInputMethod(lv.getWindowToken());
                    et_search_2.setText("");
                    et_search_2.setCursorVisible(false);
                    initTipState();
                    break;
                case R.id.tv_no_risk:
                    break;
            }
        }
    }

    /**
     * 打开基金详情页面
     */
    private void startFundDatile(QueryFundInfoBean.DataBean fundDataBean) {
        if (fundDataBean == null) {
            return;
        }
        startFundDatile(fundDataBean.getFundcode(), fundDataBean.getFundname(), fundDataBean.getFundtype(), fundDataBean.getFundstateDescription());
    }

    /**
     * 打开基金详情页面
     */
    private void startFundDatile(String fundcode, String fundname, String fundType, String fundstateDescription) {
        Intent intent = new Intent().setClass(activity, FundDetailActivity.class);
        intent.putExtra("fundcode", fundcode);
        intent.putExtra("fundname", fundname);
        intent.putExtra("fundType", fundType);
        intent.putExtra("mainTitle", fundname + " " + fundcode);
        intent.putExtra("subTitle", fundstateDescription);
        startActivity(intent);
    }

    /**
     * 打开主题热点页面
     *
     * @param size
     */
    private void startThemeHost(int size) {
        if (listThemeHotSpot == null || listThemeHotSpot.size() < (size + 1)) {
            return;
        }

        String sSelectIncome = listThemeHotSpot.get(size).getSelectIncome();//收益率名称
        if (StringUtils.isNullOrEmpty(sSelectIncome) || "null".equals(sSelectIncome)) {
            Intent intent = new Intent(activity, ThemeHotSpotActivity.class);
            intent.putExtra("head", listThemeHotSpot.get(size).getHostHead());
            intent.putExtra("url", listThemeHotSpot.get(size).getUrl());
            startActivity(intent);
        } else {
            String sFundCode = listThemeHotSpot.get(size).getFundCode();
            String fundname = listThemeHotSpot.get(size).getFundName();
            String fundType = listThemeHotSpot.get(size).getFundtype();
            String fundstateDescription = listThemeHotSpot.get(size).getFundstateDescription();
            if (!StringUtils.isNullOrEmpty(sFundCode)) {
                if (!StringUtils.isNullOrEmpty(fundname)
                        && !StringUtils.isNullOrEmpty(fundType)
                        && !StringUtils.isNullOrEmpty(fundstateDescription)) {
                    startFundDatile(sFundCode, fundname, fundType, fundstateDescription);
                } else {
                    queryFundInfo(sFundCode);
                }
            }
        }
    }

    /**
     * 开户
     */
    private final static String REGISTER = "register";
    /**
     * 登录
     */
    private final static String LOGIN = "login";
    /**
     * 客服
     */
    private final static String SERVICES = "services";
    /**
     * 点击用户头像
     */
    private final static String CLICK_USER_HEAD = "click_user_head";
    /**
     * 公告标题
     */
    private final static String NOTICE = "notice";
    /**
     * 理财视点更多
     */
    private final static String FINANCIAL_MORE = "financial_more";
    /**
     * 理财视点更多
     */
    private final static String USER_EDIT = "user_edit";

    private void openActivity(String type) {
        Intent intent = null;
        if (REGISTER.equals(type)) {  //注册
            ActivityUtils.gotoRegisterStep1_1Activity(activity);
        } else if (LOGIN.equals(type)) { //登录
            String userId = UserBeanUtil.getInstance().getLastLoginAndRecordUserId();
            ActivityUtils.gotoLogin(activity, !StringUtils.isNullOrEmpty(userId), false, userId);
        } else if (SERVICES.equals(type)) { //客服
            onlineType();
        } else if (CLICK_USER_HEAD.equals(type)) { //点击头像
            intent = new Intent(activity, UserSettingActivity.class);
            startActivity(intent);
        } else if (NOTICE.equals(type)) {
            showToast("点击公告标题" + tv_home_notice_content.getCurTipIndex());

        } else if (FINANCIAL_MORE.equals(type)) {
            intent = new Intent(activity, FinancialServicesListActivity.class);
            startActivity(intent);
        } else if (USER_EDIT.equals(type)) {
            intent = new Intent(activity, UserInfoEditActivity.class);
            startActivity(intent);
        }
    }

    private void onlineType() {

        IcbcDialog dialog = new IcbcDialog(activity);
        dialog.setAnimationEnable(true);
        dialog.setCancelable(false);
        dialog.showClose();
        dialog.setTitle("提示");
        dialog.setContentText("您可以选择在线客服或者24小时客服电话进行咨询。");
        dialog.setEditTextType(false);
        dialog.setNegativeListener("客服电话", new IcbcDialog.OnNegativeListener() {
            @Override
            public void onClick(IcbcDialog dialog) {
                dialog.dismiss();
                activity.callCustomerServiceTelephoneNumbers();
            }
        });
        dialog.setPositiveListener("在线客服", new IcbcDialog.OnPositiveListener() {
            @Override
            public void onClick(IcbcDialog dialog) {
                dialog.dismiss();
                activity.onlineCustomer();
            }
        }).show();
    }


    /**
     * 展示公告信息-5秒一展示
     */
    private void showAnnouncemets() {
        if (listAnnouncemetsTitle == null) {
            listAnnouncemetsTitle = new ArrayList<String>();
        }

        tv_home_notice_content.setTipList(activity, listAnnouncemets);
    }

    ///////////////////////////接口获取数据///////////////////
    /**
     * 公告列表
     */
    private List<ListAnnouncemetsBean.DataBean> listAnnouncemets;
    private List<String> listAnnouncemetsTitle;

    /**
     * 查询基金详情
     */
    private void queryFundInfo(final String fundCode) {
        if (StringUtils.isNullOrEmpty(fundCode)) {
            return;
        }
        Map<String, String> params = new HashMap<>();
        params.put("fundCode", fundCode);
        OkGo.<String>post(HostConstant.QUERY_FUND_INFO)
                .tag(this)
                .params(HttpUtils.getCommonParams(activity, params))
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(Response<String> response) {
                        parseJson_fund(response.body());
                    }


                    @Override
                    public void onError(Response<String> response) {
                        super.onError(response);
                        activity.showToast("网络加载失败，请稍后再试!");
                    }

                    @Override
                    public void onFinish() {
                        super.onFinish();
                    }
                });
    }

    /**
     * 查询公告
     */
    private void listAnnouncemets() {
        Map<String, String> params = new HashMap<>();
        params.put("pageNum", "1");
        OkGo.<String>post(HostConstant.LIST_ANNOUNCEMETS)
                .tag(this)
                .params(HttpUtils.getCommonParams(activity, params))
                .cacheKey(AESUtils.encrypt("isCacheHomeNotices", HostConstant.LIST_ANNOUNCEMETS))
                .cacheMode(CacheMode.FIRST_CACHE_THEN_REQUEST)
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(Response<String> response) {
                        parseJson_announcemets(response.body());
                    }

                    @Override
                    public void onCacheSuccess(Response<String> response) {
                        super.onCacheSuccess(response);
                        if (!isCacheHomeNotices) {
                            onSuccess(response);
                            isCacheHomeNotices = true;
                        }
                    }

                    @Override
                    public void onError(Response<String> response) {
                        super.onError(response);
                        activity.showToast("网络加载失败，请稍后再试!");
                    }

                    @Override
                    public void onFinish() {
                        super.onFinish();
                    }
                });
    }

    /**
     * 查询主题热点
     */
    private void queryThemeHotSpotList() {
        OkGo.<String>post(HostConstant.QUERY_THEME_HOT_SPOT_LIST)
                .tag(this)
                .params(HttpUtils.getCommonParams(activity, null))
                .cacheKey(AESUtils.encrypt("isCacheHomeThemeHot", HostConstant.QUERY_THEME_HOT_SPOT_LIST))
                .cacheMode(CacheMode.FIRST_CACHE_THEN_REQUEST)
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(Response<String> response) {
                        parseJson_hotspot(response.body());
                    }

                    @Override
                    public void onCacheSuccess(Response<String> response) {
                        super.onCacheSuccess(response);
                        if (!isCacheHomeThemeHot) {
                            //一般来说,缓存回调成功和网络回调成功做的事情是一样的,所以这里直接回调onSuccess
                            onSuccess(response);
                            isCacheHomeThemeHot = true;
                        }
                    }

                    @Override
                    public void onError(Response<String> response) {
                        super.onError(response);
                        activity.showToast("网络加载失败，请稍后再试!");
                    }

                    @Override
                    public void onFinish() {
                        super.onFinish();
                        refreshComplete();
                    }
                });

    }

    /**
     * 查询新闻资讯
     */
    private void queryManagerMoneyViewList() {
        OkGo.<String>post(HostConstant.QUERY_MANAGER_MONEY_VIEW_LIST)
                .tag(this)
                .params(HttpUtils.getCommonParams(activity, null))
                .cacheKey(AESUtils.encrypt("isCacheHomeNews", HostConstant.QUERY_MANAGER_MONEY_VIEW_LIST))
                .cacheMode(CacheMode.FIRST_CACHE_THEN_REQUEST)
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(Response<String> response) {
                        parseJson_money(response.body());
                    }

                    @Override
                    public void onCacheSuccess(Response<String> response) {
                        super.onCacheSuccess(response);
                        if (!isCacheHomeNews) {
                            //一般来说,缓存回调成功和网络回调成功做的事情是一样的,所以这里直接回调onSuccess
                            onSuccess(response);
                            isCacheHomeNews = true;
                        }
                    }

                    @Override
                    public void onError(Response<String> response) {
                        super.onError(response);
                        activity.showToast("网络加载失败，请稍后再试!");
                    }

                    @Override
                    public void onFinish() {
                        refreshComplete();
                    }
                });

    }
    ///////////////////////////解析接口返回数据///////////////////

    private QueryUserAssetsBean.DataBean.ListBean xjkxListBean;
    private QueryUserAssetsBean.DataBean.ListBean cjxjkxListBean;

    /**
     * 解析查询资产接口返回的数据
     */
    private void parseJson_assets(QueryUserAssetsBean bean) {//0220 eventBuss
        if (bean == null) {
            return;
        }
        BigDecimal decimal = new BigDecimal(0);
        BigDecimal decimalTotalAssets = new BigDecimal(0);
        String sTotalAccount_pri = bean.getData().getTotalAssets();
        sTotalAccount = bean.getData().getTotalAssets();
        try {
            decimalTotalAssets = new BigDecimal(sTotalAccount);
        } catch (Exception e) {
            e.printStackTrace();
        }
        if (StringUtils.isNullOrEmpty(bean.getData().getTotalIncome()) || "null".equals(bean.getData().getTotalIncome())) {
            sYesterDayIncome = "0.00";
        } else {
            sYesterDayIncome = StringUtils.insertComma(bean.getData().getTotalIncome(), -1) + "";
        }
        if (!((HomeActivity) activity).getShowTotalAccountStatus()) {
            tv_yesterday_income_val.setText(MentorConst.NOT_SHOW_ACCOUNT_STR);
        } else {
            tv_yesterday_income_val.setText(sYesterDayIncome);
        }
        try {
            if (StringUtils.isNullOrEmpty(sTotalAccount) || "null".equals(sTotalAccount)) {
                tv_total_account_decimal_val.setText(".00");
                sTotalAccount = "0";
            } else {
                if (sTotalAccount.contains(".")) {
                    tv_total_account_decimal_val.setText("" + sTotalAccount.substring(sTotalAccount.lastIndexOf(".")));
                    sTotalAccount = sTotalAccount.substring(0, sTotalAccount.lastIndexOf("."));
                }
                sTotalAccount = StringUtils.insertComma(sTotalAccount, 0);
            }
            if (image_is_show_total_account.getTag() == null || "show".equals(image_is_show_total_account.getTag().toString())) {
                tv_total_account_val.setText("" + sTotalAccount);
            } else {
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        ////////////////////////////////////////

        String strXJKX_lastincome = null;// 现金快线代码 482002的昨日收益
        BigDecimal decimalXJKX_lastincome = new BigDecimal(0);// 现金快线代码 482002的昨日收益
        String strCJXJKX_lastincome = null;//超级现金快线带啊 000677 的昨日收益
        BigDecimal decimalCJXJKX_lastincome = new BigDecimal(0);//超级现金快线带啊 000677 的昨日收益
        String sXJKXCurrentRemainShare = null;// 现金快线代码 482002 的资产
        String sCJXJKXCurrentRemainShare = null;// 超级现金快线 000677 的资产
        String cash = "";//现金快线最终显示昨日收益
        String super_cash = "";//超级现金快线最终显示昨日收益

        xjkxListBean = null;
        cjxjkxListBean = null;
        strXJKX_lastincome = bean.getData().getCashExpressProfit();
        if (!StringUtils.isNullOrEmpty(strXJKX_lastincome) && !"null".equals(strXJKX_lastincome)) {// 现金快线代码 482002的昨日收益
            decimalXJKX_lastincome = decimalXJKX_lastincome.add(new BigDecimal(strXJKX_lastincome));
            cash = strXJKX_lastincome;
        } else {
            cash = "0.00";
        }
        strCJXJKX_lastincome = bean.getData().getSuperCashExpressProfit();
        if (!StringUtils.isNullOrEmpty(strCJXJKX_lastincome) && !"null".equals(strCJXJKX_lastincome)) {//超级现金快线带啊 000677 的昨日收益
            decimalCJXJKX_lastincome = decimalCJXJKX_lastincome.add(new BigDecimal(strCJXJKX_lastincome));
            super_cash = strCJXJKX_lastincome;
        } else {
            super_cash = "0.00";
        }

        sXJKXCurrentRemainShare = bean.getData().getCashExpressProperty();// 现金快线代码 482002 的资产
        sCJXJKXCurrentRemainShare = bean.getData().getSuperCashExpressProperty();// 超级现金快线 000677 的资产

        if (!StringUtils.isNullOrEmpty(sXJKXCurrentRemainShare) && !"null".equals(sXJKXCurrentRemainShare)) {
            sXJKXCurrentRemainShare = StringUtils.insertComma(sXJKXCurrentRemainShare, -1);
        } else {
            sXJKXCurrentRemainShare = "0.00";
        }
        if (!StringUtils.isNullOrEmpty(sCJXJKXCurrentRemainShare) && !"null".equals(sCJXJKXCurrentRemainShare)) {
            sCJXJKXCurrentRemainShare = StringUtils.insertComma(sCJXJKXCurrentRemainShare, -1);
        } else {
            sCJXJKXCurrentRemainShare = "0.00";
        }

        if (!StringUtils.isNullOrEmpty(strXJKX_lastincome) && !"null".equals(strXJKX_lastincome)) {
            cash = (decimalXJKX_lastincome.doubleValue() > 0 ? "+" : "") + StringUtils.insertComma(cash, -1);
        }
        if (!StringUtils.isNullOrEmpty(strCJXJKX_lastincome) && !"null".equals(strCJXJKX_lastincome)) {
            super_cash = (decimalCJXJKX_lastincome.doubleValue() > 0 ? "+" : "") + StringUtils.insertComma(super_cash, -1);
        }
        sHomeCashTotal = sXJKXCurrentRemainShare;//现金快线 总额
        sHomeCash = cash;//现金快线 正负
        sHomeSuperCashTotal = sCJXJKXCurrentRemainShare;//超级现金快线 总额
        sHomeSuperCash = super_cash;//超级现金快线 正负

        if (bean.getData().getList() != null) {
            for (QueryUserAssetsBean.DataBean.ListBean mod : bean.getData().getList()) {
                try {
                    if (HostConstant.XJKJ_CODE.equals(mod.getFundCode()) && !StringUtils.isNullOrEmpty(mod.getFundCode())) {//现金快线
                        xjkxListBean = mod;
                        continue;
                    } else if (HostConstant.CJXJKJ_CODE.equals(mod.getFundCode()) && !StringUtils.isNullOrEmpty(mod.getFundCode())) {//超级现金快线
                        cjxjkxListBean = mod;
                        continue;
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
    }

    private QueryFundInfoBean.DataBean XJKJDataBean;  //现金快线
    private QueryFundInfoBean.DataBean CJXJKJDataBean; //超级现金快线

    /**
     * 解析从查询基金详情接口返回的数据
     *
     * @param json
     */
    private void parseJson_fund(String json) {
        QueryFundInfoBean bean;
        try {
            bean = new Gson().fromJson(json, QueryFundInfoBean.class);
        } catch (Exception exception) {
            activity.showConfirmAlert(activity, "提示", "数据解析错误");
            return;
        }

        if (!CommonUtil.checkState(activity, bean, json)) {
            return;
        }

        if (bean == null || bean.getData() == null) {
            activity.showConfirmAlert(activity, "提示", getString(R.string.no_data));
            return;
        }
        parseJson_fund_bean(bean);
    }

    private void parseJson_fund_bean(QueryFundInfoBean bean) {
        if (bean == null) {
            return;
        }
        if (HostConstant.XJKJ_CODE.equals(bean.getData().getFundcode())) {
            if (StringUtils.isNullOrEmpty(bean.getData().getIncomeratio()) || "null".equals(bean.getData().getIncomeratio())) {
                tv_home_seven_the_year_val.setText("--");
            } else {
                tv_home_seven_the_year_val.setText("" + bean.getData().getIncomeratio());
            }
            XJKJDataBean = bean.getData();
        } else if (HostConstant.CJXJKJ_CODE.equals(bean.getData().getFundcode())) {
            if (StringUtils.isNullOrEmpty(bean.getData().getIncomeratio()) || "null".equals(bean.getData().getIncomeratio())) {
                tv_home_super_seven_the_year_val.setText("--");
            } else {
                tv_home_super_seven_the_year_val.setText("" + bean.getData().getIncomeratio());
            }
            CJXJKJDataBean = bean.getData();
        } else {
            startFundDatile(bean.getData());
        }

    }

    /**
     * 解析从查询基金详情接口返回的数据
     *
     * @param json
     */
    private void parseJson_announcemets(String json) {
        ListAnnouncemetsBean bean;
        try {
            bean = new Gson().fromJson(json, ListAnnouncemetsBean.class);
        } catch (Exception exception) {
            activity.showConfirmAlert(activity, "提示", "数据解析错误");
            return;
        }

        if (!CommonUtil.checkState(activity, bean, json)) {
            return;
        }

        if (bean == null || bean.getData() == null) {
            activity.showConfirmAlert(activity, "提示", getString(R.string.no_data));
            return;
        }

        if (bean.getData().size() == 0) {
            ll_home_notice_container.setVisibility(View.GONE);
        } else {
            ll_home_notice_container.setVisibility(View.VISIBLE);
        }
        MentorLogger.Log("lty", "公告数据集合大小" + bean.getData().size());
        if (listAnnouncemets != null) {
            listAnnouncemets.clear();
        }
        listAnnouncemets = bean.getData();
        showAnnouncemets();
    }

    /**
     * 解析从查询主题热点接口返回的数据
     *
     * @param json
     */
    private void parseJson_hotspot(String json) {
        QueryThemeHotSpotListBean bean;
        try {
            bean = new Gson().fromJson(json, QueryThemeHotSpotListBean.class);
        } catch (Exception exception) {
            activity.showConfirmAlert(activity, "提示", "数据解析错误");
            return;
        }

        if (!CommonUtil.checkState(activity, bean, json)) {
            return;
        }

        if (bean == null || bean.getData() == null || bean.getData().getData() == null) {
            return;
        }
        listThemeHotSpot = bean.getData().getData();
        /////////////////////////////////////////ll_home_hot_spot_layout
        ll_home_hot_spot_layout.removeAllViews();
        Uri uriHotSpot = null;

        for (int i = 0; i < bean.getData().getData().size(); i++) {
            uriHotSpot = null;
            View viewThemeHotSpot = View.inflate(activity, R.layout.item_home_theme_hot_spot, null);
            SimpleDraweeView civ_hot_spot = (SimpleDraweeView) viewThemeHotSpot.findViewById(R.id.civ_hot_spot);
            TextView tv_home_hot_spot_title = (TextView) viewThemeHotSpot.findViewById(R.id.tv_home_hot_spot_title);
            TextView tv_home_hot_spot_reason = (TextView) viewThemeHotSpot.findViewById(R.id.tv_home_hot_spot_reason);
            LinearLayout ll_hot_spot_income_layout = (LinearLayout) viewThemeHotSpot.findViewById(R.id.ll_hot_spot_income_layout);//收益率值
            TextView tv_hot_spot_income_val = (TextView) viewThemeHotSpot.findViewById(R.id.tv_hot_spot_income_val);//收益率值
            TextView tv_hot_spot_income_val_bfh = (TextView) viewThemeHotSpot.findViewById(R.id.tv_hot_spot_income_val_bfh);//收益率值

            TextView tv_hot_spot_income_name = (TextView) viewThemeHotSpot.findViewById(R.id.tv_hot_spot_income_name);//收益率名称
            LinearLayout ll_home_hot_spot_flag = (LinearLayout) viewThemeHotSpot.findViewById(R.id
                    .ll_home_hot_spot_flag); //标签容器
            View view_home_hot_spot_line = viewThemeHotSpot.findViewById(R.id.view_home_hot_spot_line);
            tv_home_hot_spot_title.setText(bean.getData().getData().get(i).getHostHead() + "");
            tv_home_hot_spot_reason.setText(bean.getData().getData().get(i).getDeputyHead() + "");

            String sSelectIncome = bean.getData().getData().get(i).getSelectIncome();//收益率名称
            if (StringUtils.isNullOrEmpty(sSelectIncome) || "null".equals(sSelectIncome)) {
                if (!StringUtils.isNullOrEmpty(bean.getData().getData().get(i).getCategoryImg())) {
                    try {
                        uriHotSpot = Uri.parse(bean.getData().getData().get(i).getCategoryImg());
                    } catch (Exception e) {
                        uriHotSpot = null;
                        e.printStackTrace();
                    }
                    if (uriHotSpot != null) {
                        civ_hot_spot.setImageURI(uriHotSpot);
                    }
                }
                civ_hot_spot.setVisibility(View.VISIBLE);
                ll_hot_spot_income_layout.setVisibility(View.GONE);//2017\06\12 add
                tv_hot_spot_income_val.setVisibility(View.GONE);
                tv_hot_spot_income_name.setVisibility(View.GONE);
            } else {
                String selectIncomeValue = bean.getData().getData().get(i).getSelectIncomeValue();

                tv_hot_spot_income_val.setText(StringUtils.insertComma(selectIncomeValue.replace("%", "")));
                if (selectIncomeValue.contains("%")) {
                    tv_hot_spot_income_val_bfh.setText("%");
                } else {
                    tv_hot_spot_income_val_bfh.setText("");
                }
                if (bean.getData().getData().get(i).getSelectIncomeValue().contains("-")) {
                    tv_hot_spot_income_val.setTextColor(getResources().getColor(R.color.black));
                    tv_hot_spot_income_val_bfh.setTextColor(getResources().getColor(R.color.black));
                } else {
                    tv_hot_spot_income_val.setTextColor(getResources().getColor(R.color.bg_btn_red));
                    tv_hot_spot_income_val_bfh.setTextColor(getResources().getColor(R.color.bg_btn_red));
                }
                tv_hot_spot_income_name.setText(sSelectIncome);
                civ_hot_spot.setVisibility(View.INVISIBLE);
                ll_hot_spot_income_layout.setVisibility(View.VISIBLE);//2017\06\12 add
                tv_hot_spot_income_val.setVisibility(View.VISIBLE);
                tv_hot_spot_income_name.setVisibility(View.VISIBLE);
            }
            view_home_hot_spot_line.setVisibility(View.VISIBLE);
            if ((i + 1) == bean.getData().getData().size()) { //最后一条数据将分割线隐藏
                view_home_hot_spot_line.setVisibility(View.GONE);
            }

            //获取标签数据,格式化为数组,遍历将生成的文字标签添加到容器
            if (!StringUtils.isNullOrEmpty(bean.getData().getData().get(i).getTags())) {
                String[] arry = bean.getData().getData().get(i).getTags().split(",");
                for (int j = 0; j < arry.length; j++) {
                    ll_home_hot_spot_flag.addView(generTextViewFlag(j, arry[j] + ""));
                }
            }
            final int index = i;
            viewThemeHotSpot.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    startThemeHost(index);
                }
            });

            ll_home_hot_spot_layout.addView(viewThemeHotSpot);

        }
    }

    /**
     * 理财视点
     */
    private List<QueryManagerMoneyViewListBean.DataBean.DataListBean> listManagerMoneyView;

    /**
     * 解析从查询理财视点接口返回的数据
     *
     * @param json
     */
    private void parseJson_money(String json) {
        QueryManagerMoneyViewListBean bean;
        try {
            bean = new Gson().fromJson(json, QueryManagerMoneyViewListBean.class);
        } catch (Exception exception) {
            activity.showConfirmAlert(activity, "提示", "数据解析错误");
            return;
        }

        if (!CommonUtil.checkState(activity, bean, json)) {
            return;
        }

        if (bean == null || bean.getData() == null || bean.getData().getData() == null) {
            return;
        }
        listManagerMoneyView = bean.getData().getData();
        int iCount = bean.getData().getData().size() - 1;
        for (int i = iCount; i > 2; i--) {
            bean.getData().getData().remove(i);
        }
        LinearLayout.LayoutParams params = (LinearLayout.LayoutParams) lv_financial.getLayoutParams();
        params.height = listManagerMoneyView.size() * 30 * 2 + listManagerMoneyView.size() * 1;
        lv_financial.setLayoutParams(params);
        homeFinancialNewAdapter = new HomeFinancialNewAdapter(activity, bean.getData().getData());
        lv_financial.setAdapter(homeFinancialNewAdapter);
        lv_financial.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                if (listManagerMoneyView == null || listManagerMoneyView.size() <= position) {
                    return;
                }
                Intent intent = new Intent(activity, FinancialServicesActivity.class);
                intent.putExtra("head", listManagerMoneyView.get(position).getHead());
                intent.putExtra("id", "" + listManagerMoneyView.get(position).getId());
                intent.putExtra("url", listManagerMoneyView.get(position).getUrl());
                startActivity(intent);
            }
        });
    }

    @Override
    public void onHeaderRefresh(PullToRefreshView view) {
        initData(true);
    }

    private void refreshComplete() {
        pullToRefreshView.onHeaderRefreshComplete();
    }


    private String sYesterDayIncome = "";//昨日收益
    private String sHomeCashTotal = "";//现金快线 总额
    private String sHomeCash = "";//现金快线 正负
    private String sHomeSuperCashTotal = "";//超级现金快线 总额
    private String sHomeSuperCash = "";//超级现金快线 正负

    /**
     * 设置总资产的状态(是否是铭文显示)
     *
     * @param flag boolean
     */
    public void setIsShowTotalAccount(boolean flag) {
        if (!flag) {
            image_is_show_total_account.setTag("notshow");
            tv_total_account_val.setText(MentorConst.NOT_SHOW_ACCOUNT_STR);
            tv_total_account_decimal_val.setVisibility(View.GONE);
            tv_yesterday_income_val.setText(MentorConst.NOT_SHOW_ACCOUNT_STR);
            image_is_show_total_account.setImageResource(R.drawable.ic_home_show_account_white);
        } else {
            image_is_show_total_account.setTag("show");
            tv_total_account_val.setText("" + (StringUtils.isNullOrEmpty(sTotalAccount) ? "" : sTotalAccount));
            tv_total_account_decimal_val.setVisibility(View.VISIBLE);
            tv_yesterday_income_val.setText(sYesterDayIncome);
            image_is_show_total_account.setImageResource(R.drawable.ic_home_no_show_account_white);
        }
    }


    @Subscribe
    public void onEvent(InterfaceCallback ic) {
//        Log.e("CallBack","HomTab"+"回调");
        if (ic == null || ic.getObj() == null) {
            return;
        }
        Object obj = ic.getObj();
        String sCallBackType = ic.getCallBackType();

        if (HostConstant.QUERY_USER_ASSETS.equals(obj)) {
            if (InterfaceCallback.SUCCESS.equals(sCallBackType)) {
//                Log.e("CallBack","HomTab"+"用户个人资产获取成功");
                parseJson_assets(getQueryUserAssetsBean());
            }
        } else if ((HostConstant.QUERY_FUND_INFO + "_" + HostConstant.XJKJ_CODE).equals(obj)) {//现金快线
            if (InterfaceCallback.SUCCESS.equals(sCallBackType)) {
//                Log.e("CallBack","HomTab"+"现金快线获取成功");
                parseJson_fund_bean(getXJKJDataBean());
            }
        } else if ((HostConstant.QUERY_FUND_INFO + "_" + HostConstant.CJXJKJ_CODE).equals(obj)) {//超级现金快线
            if (InterfaceCallback.SUCCESS.equals(sCallBackType)) {
//                Log.e("CallBack","HomTab"+"超级现金快线获取成功");
                parseJson_fund_bean(getCJXJKJDataBean());
            }
        } else if ((HostConstant.ANTIMONEY_VALIDATE).equals(obj)) {//反洗钱
            if (InterfaceCallback.SUCCESS.equals(sCallBackType)) {
                parseJson_moneyValidate_bean(((HomeActivity) activity).getAntiMoneyValidateBean());
            }
        } else if (HostConstant.QUERY_RISK_LEVEL.equals(obj)) {
            if (InterfaceCallback.SUCCESS.equals(sCallBackType)) {
//                Log.e("CallBack","HomTab"+"用户风险等级获取成功");
                parseJson_level(getQueryRiskLevelBean());
            }
        } else if (CommentConfig.ID_CARD_TITPS.equals(obj)) {
            if (InterfaceCallback.SUCCESS.equals(sCallBackType)) {
                if (!StringUtils.isNullOrEmpty(activity.mentorApplication.getAccountLoginBean().getData().getCertificateExpireMessage())) {
                    activity.showConfirmAlert(activity, "温馨提示",
                            String.format(activity.getResources().getString(R.string.string_certificateExpire_Message),
                                    activity.mentorApplication.userBean.getUserName()), "关闭", "立即更新");
                }
            }
        }

    }

    private boolean isMoneyValidate = false; //是否反洗钱成功,个人资料
    private boolean islevelValidate = false; //是否风险评测

    /**
     * 解析返回的 用户风险等级json
     */
    private void parseJson_level(QueryRiskLevelBean bean) {//0620 eventBust
        if (bean == null) {
            return;
        }
        String userRiskLevleName = bean.getData().getLevelName();
        if (StringUtils.isNullOrEmpty(userRiskLevleName)) { //没有风险评测
            islevelValidate = false;
        } else {
            islevelValidate = true;
        }
        initTipState();
    }

    /**
     * 显示反洗钱的提示,请补充个人信息
     *
     * @param bean
     */
    private void parseJson_moneyValidate_bean(AntiMoneyValidateBean bean) {
        if (bean == null) {
            return;
        }
        if ("0000".equals(bean.getErrorCode())) {
            isMoneyValidate = true;
        } else {
            isMoneyValidate = false;
        }
        PreferencesUtils.putString(activity, activity.mentorApplication.getAccountLoginBean().getData().getIdentityNo() +
                "isMoneyValidate", isMoneyValidate + ":" + bean.getErrorMessage());
        initTipState();
    }

    public void initTipState() {
        if (isMoneyValidate) {
            if (islevelValidate) {
                tv_no_risk.setVisibility(View.GONE);
            } else {
                tv_no_risk.setVisibility(View.VISIBLE);
                tv_no_risk.setText("请进行风险评测");
            }
        } else {
            tv_no_risk.setVisibility(View.VISIBLE);
            tv_no_risk.setText("请补充个人资料");
        }
        if (isSearchLayoutShow()) {
            tv_no_risk.setVisibility(View.GONE);
        }
    }

    //////////////////////通知HomeActivity获取数据

    /**
     * 风险评测
     */
    private void queryRiskLevelHome() {
        ((HomeActivity) activity).queryRiskLevel();
    }

    /**
     * 反洗钱
     */
    private void queryAntiMoneyValidateHome() {
        ((HomeActivity) activity).queryAntiMoneyValidate();
    }

    /**
     * 个人资产
     */
    private void queryUserAssetsHome() {
        ((HomeActivity) activity).queryUserAssets();
    }

    private void queryFundInfoHome(String fundCode) {
        ((HomeActivity) activity).queryFundInfo(fundCode);
    }
    ///////////////////////获取HomeActivity里的 个人资产、风险评测对象

    /**
     * 风险评测
     *
     * @return
     */
    private QueryRiskLevelBean getQueryRiskLevelBean() {
        return ((HomeActivity) activity).getQueryRiskLevelBean();
    }

    /**
     * 个人资产
     *
     * @return
     */
    private QueryUserAssetsBean getQueryUserAssetsBean() {
        return ((HomeActivity) activity).getQueryUserAssetsBean();
    }

    /**
     * 获取基金详情--现金快线
     *
     * @return
     */
    private QueryFundInfoBean getXJKJDataBean() {
        return ((HomeActivity) activity).getXJKJDataBean();
    }

    /**
     * 获取基金详情--超级现金快线
     *
     * @return
     */
    private QueryFundInfoBean getCJXJKJDataBean() {
        return ((HomeActivity) activity).getCJXJKJDataBean();
    }

    public boolean isSearchLayoutShow() {
        if (ll_all_fund_search.getVisibility() == View.GONE) {
            return false;
        } else {
            return true;
        }
    }

    public void hideSearchLayout() {
        activity.collapseSoftInputMethod(lv.getWindowToken());
        et_search_1.setText("");
        et_search_1.setCursorVisible(false);
        et_search_2.setText("");
        et_search_2.setCursorVisible(false);
        if (!activity.mentorApplication.needLogin())
            initTipState();
        else
            tv_no_risk.setVisibility(View.GONE);
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onHomeBannerLoginCallBack(HomeBannerLoginEvent event) {
        if (event.isSuccess) {
            if (bannersBean != null) {
                gotoBannerUrlActivity(bannersBean);
            }
        }
    }
}
